package player

import "fmt"
import "net"
import "network"
import "protocol"
import util "protocol/util"

type Receiver struct {
	logined		bool
	conn		*net.TCPConn
	buf 		*network.ReceBuffer
	senderCh	chan []byte
	playerCh	chan []byte
}

func NewReceiver(conn *net.TCPConn)(p *Receiver) {
	return &Receiver{false, conn, nil, nil, nil}
}

func (p *Receiver) Start() {
	if p.conn == nil {
		return
	}

	// create sender thread
	p.senderCh = make(chan []byte, 10)
	go Sender(p.conn, p.senderCh)

	// read socket data
	p.buf = network.NewReceBuffer(int16(1024))
	for{
		n,e := p.conn.Read(p.buf.Space())
		if e != nil {
			fmt.Println("conn lost!")
			p.conn.Close()
			break
		}
		p.buf.Put(int16(n))

		for rec := p.buf.Take(); rec != nil; rec = p.buf.Take() {
			p.handleMessage(rec)
		}
	}
}

func (p *Receiver) handleMessage(data []byte) {
	stream := util.NewByteStream(data)
	switch stream.GetType() {
	case protocol.MSG_REQUEST_LOGIN:
		p.handleLogin(stream)
	case protocol.MSG_CHAT_CONTENT:
		p.handleChat(stream)
	default:
		fmt.Println("err:", data)
	}
}

func (p *Receiver) handleLogin(stream *util.ByteStream){
	if p.logined {
		return
	}

	var msg protocol.RequestLogin
	msg.ReadFromStream(stream)
	fmt.Println("login:", msg.User)

	p.logined = true
}

func (p *Receiver) handleChat(stream *util.ByteStream){
	if !p.logined {
		return
	}

	var msg protocol.ChatContent
	msg.ReadFromStream(stream)
	fmt.Println("chat:", msg.Content)
}

